#!/usr/bin/python
# -*- coding: utf-8 -*-
#pgm.py

#License: GPLv2 or later

#Writed by v12aml
#http://code.google.com/p/pygm/


#Vars
db_file = "/home/v12aml/var/lib/pgm/db"
portagetree_paths = "{/usr/portage/,/usr/local/portage/}"

added = 0
deleted = 0
skiped = 0
fetched = 0

#Imports
import os
import popen2
import bsddb


#Functions
def e_fetch(e, skiped, fetched):
        if db[e] == str(0):
                skiped += 1
        else:
                print "-"
                print "Fetching", e[:-1]
                e_p = popen2.Popen4("ebuild %s fetch" % e[:-1])
                e_status = e_p.wait()
                print e_p.fromchild.read()
                print "Ebuild %s fetched with status %s" % (e[:-1], e_status)
                db[e] = str(e_status)
                print "-"
	        fetched += 1
        return skiped, fetched


#Collect ebuilds
print "Collecting ebuilds..."
ebuilds_finded = os.popen('find %s -type f -name *.ebuild' % portagetree_paths, 'r')


print "Opening DB..."
db = bsddb.btopen(db_file, "c")


print "Adding data into DB..."
ef = ebuilds_finded.readlines()
for e in ef:
        if db.has_key(e):
##        print "Already exixst:", e
                pass
        else:
                db[e] = "256"
                print "Added:", e[:-1]
                added += 1
db.sync()


print "Cleaning DB..."
ltd = []
while True:
        try:
                d = db.next()
        except:
#                print "oops"
                break
#        print d
        if d[0] in ef:
#                print "Skipped", d[0]
                pass
        else:
#                print "to delete: ", d[0]
                ltd.append(d[0])
for d in ltd:
        print "Deleting", d[:-1]
        del db[d]
        deleted += 1
db.sync()


print "Reopening DB..."
db.close()        
db = bsddb.btopen(db_file, "c")


print "Fetching..."
while True:
        try:
                d = db.next()
        except:
                break
        skiped, fetched = e_fetch(d[0], skiped, fetched)
db.sync()        


db.close()        


print "Added: ", added
print "Deleted: ", deleted        
print "Fetched: ", fetched
print "Skipped: ", skiped

    
#EOF
